﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Note_Assistant
{
   public class Note
    {
        //标题
        public string Title { get; set; }
        //内容
        public string Content { get; set; }
        //创建时间
        public DateTime CreatedTime { get; set; }
        //修改时间
        public DateTime ModifiedTime { get; set; }
        public string FilePath { get; private set; }

        public Note()
        {
            CreatedTime = DateTime.Now;
            ModifiedTime = DateTime.Now;
        }
        //设置文件路径
        public void SetFilePath(string path)
        {
            FilePath = path;
        }
        //保存笔记
        public void Save()
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                string safeTitle = MakeValidFileName(Title);
                FilePath = Path.Combine(
                    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
                    "EnhancedNotes",
                    $"{safeTitle}_{CreatedTime:yyyyMMddHHmmss}.rtf");
            }

            Directory.CreateDirectory(Path.GetDirectoryName(FilePath));
            File.WriteAllText(FilePath, Content);
            ModifiedTime = DateTime.Now;
        }
        //删除
        public void Delete()
        {
            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
            }
        }
        //从文件加载笔记
        public static Note LoadFromFile(string filePath)
        {
            //创建新的Note对象并设置属性
            var note = new Note
            {
                FilePath = filePath,
                Content = File.ReadAllText(filePath),
                CreatedTime = File.GetCreationTime(filePath),
                ModifiedTime = File.GetLastWriteTime(filePath)
            };
            //从文件中提取文件名
            string fileName = Path.GetFileNameWithoutExtension(filePath);
            int lastUnderscore = fileName.LastIndexOf('_');
            note.Title = lastUnderscore > 0 ? fileName.Substring(0, lastUnderscore) : fileName;

            return note;
        }

        //非法字符替换为下划线
        private string MakeValidFileName(string name)
        {
            foreach (char c in Path.GetInvalidFileNameChars())
            {
                name = name.Replace(c, '_');
            }
            return name;
        }

    }
}
